package com.zx.BookSeaReader.ui.booklist;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zx.BookSeaReader.R;
import com.zx.BookSeaReader.base.BaseActivity;
import com.zx.BookSeaReader.common.APPCONST;
import com.zx.BookSeaReader.greendao.entity.BookListBean;
import com.zx.BookSeaReader.greendao.entity.UserBean;
import com.zx.BookSeaReader.greendao.service.BookListService;
import com.zx.BookSeaReader.ui.booklistdetail.BookListDetailActivity;
import com.zx.BookSeaReader.util.StringHelper;
import com.zx.BookSeaReader.util.TextHelper;
import com.zx.BookSeaReader.widget.RefreshLayout;
import com.zx.BookSeaReader.widget.itemdecoration.DividerItemDecoration;

import java.util.List;

public class BookListActivity extends BaseActivity {

    @BindView(R.id.refresh_layout)
    RefreshLayout mRlRefresh;
    @BindView(R.id.refresh_rv_content)
    RecyclerView mRvBookList;
    @BindView(R.id.tv_title_text)
    TextView mTvTitle;

    @BindView(R.id.tv_new_create)
    TextView mTvNewCreate;
    @BindView(R.id.tv_most_love)
    TextView mTvMostLove;
    @BindView(R.id.et_search_key)
    EditText etSearchKey;
    @BindView(R.id.tv_search_conform)
    ImageView tvSearchConform;

    @BindView(R.id.ll_title_back)
    LinearLayout llTitleBack;

    private UserBean userBean;
    private int style=1;
    private String searchKey;
    private BookListService mBookListService;
    private List<BookListBean> mBookListBeans;
    private BookListAdapter mBookListAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_list);
        ButterKnife.bind(this);
        mBookListAdapter = new BookListAdapter();
        mBookListService=new BookListService();
        mTvTitle.setText("书单交流列表");
        userBean = (UserBean)getIntent().getSerializableExtra(APPCONST.USER);
        mTvNewCreate.setTextColor(ContextCompat.getColor(this,R.color.colorAccent));

        mRvBookList.setLayoutManager(new LinearLayoutManager(this));
        mRvBookList.addItemDecoration(new DividerItemDecoration(this));
        mRvBookList.setAdapter(mBookListAdapter);

        mRlRefresh.setBackground(ContextCompat.getDrawable(this,R.color.white));
        //mRlRefresh.setVisibility(View.GONE);
        mRlRefresh.setVisibility(View.VISIBLE);
        mRlRefresh.showFinish();
       // mRlRefresh.showLoading();
//        mBookListAdapter.refreshItems(mBookListBeans);
        initClick();

    }

    @Override
    public void onResume() {
        super.onResume();
        mBookListBeans = mBookListService.getAllVisibleBookLists();
        mBookListAdapter.refreshItems(mBookListBeans);
    }

    protected void initClick(){
        llTitleBack.setOnClickListener(
                (v) ->{
                    finish();
                }
        );
        mTvNewCreate.setOnClickListener(
                (v) ->{
                    style=1;
                    mTvMostLove.setTextColor(ContextCompat.getColor(this,R.color.textdefault));
                    mTvNewCreate.setTextColor(ContextCompat.getColor(this,R.color.colorPrimary));
                    if (StringHelper.isEmpty(searchKey)) {
                        mBookListBeans = mBookListService.getAllVisibleBookLists();
                    }else {
                        mBookListBeans = mBookListService.getLikeBookListsByTime(searchKey);
                    }
                    mBookListAdapter.refreshItems(mBookListBeans);
        });
        mTvMostLove.setOnClickListener(
                (v) ->{
                    style=2;
                    mTvNewCreate.setTextColor(ContextCompat.getColor(this,R.color.textdefault));
                    mTvMostLove.setTextColor(ContextCompat.getColor(this,R.color.colorPrimary));
                    if (StringHelper.isEmpty(searchKey)) {
                        mBookListBeans = mBookListService.getAllVisibleBookListsByLoveCount();

                    }else {
                        mBookListBeans = mBookListService.getLikeBookListsByLoveCount(searchKey);
                    }
                    mBookListAdapter.refreshItems(mBookListBeans);

                });
        etSearchKey.setOnKeyListener((v, keyCode, event) -> {
            //是否是回车键
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                //隐藏键盘
                ((InputMethodManager) this.getSystemService(INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(this.getCurrentFocus()
                                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                //搜索
                search();
            }
            return false;
        });
        tvSearchConform.setOnClickListener(view -> search());
        etSearchKey.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(final Editable editable) {
                searchKey = editable.toString();
//                if (StringHelper.isEmpty(searchKey)) {
//                    search();
//                }

            }

        });
        mBookListAdapter.setOnItemClickListener(
                (view, pos) -> {
                    Intent intent = new Intent(this, BookListDetailActivity.class);
                    intent.putExtra(APPCONST.BOOKLIST, mBookListAdapter.getItem(pos));
                    intent.putExtra(APPCONST.USER, userBean);
                    this.startActivity(intent);
                }
        );

        mBookListAdapter.setOnItemLongClickListener(
                (v, pos) -> {
                    openItemDialog(mBookListAdapter.getItem(pos));
                    return true;
                }
        );
    }

    /**
     * 搜索
     */
    private void search() {
        if (StringHelper.isEmpty(searchKey)) {
            mBookListBeans = mBookListService.getAllVisibleBookLists();
            style=1;
            mBookListAdapter.refreshItems(mBookListBeans);
        } else {
            if ( style==1){
                mBookListBeans = mBookListService.getLikeBookListsByTime(searchKey);
            }else {
                mBookListBeans = mBookListService.getLikeBookListsByLoveCount(searchKey);
            }

            mBookListAdapter.refreshItems(mBookListBeans);
        }
    }

    private void openItemDialog(BookListBean bookListBean) {
        String[] menus;
        menus = getResources().getStringArray(R.array.menu_long_book_list_click);
        AlertDialog labelBeanDialog = new AlertDialog.Builder(this)
                .setTitle(bookListBean.getTitle())
                .setAdapter(new ArrayAdapter<String>(this,
                                android.R.layout.simple_list_item_1, menus),
                        (dialog, which) -> onItemMenuClick(menus[which], bookListBean))
                .setNegativeButton(null, null)
                .setPositiveButton(null, null)
                .create();

        labelBeanDialog.show();
    }
    private void onItemMenuClick(String which, BookListBean bookListBean) {
        switch (which) {
            case "订阅":

                if(bookListBean.getUsername().equals(userBean.getUsername())){
                    TextHelper.showText("此书单贴是你的，无需订阅！");
                }else {
                    boolean isSubscribe = mBookListService.isBookListSub(bookListBean,userBean);
                    if(isSubscribe){
                        TextHelper.showText("你已订阅此书单贴，无需再次订阅！");
                    }else {
                        mBookListService.addSubscribeBookList(bookListBean,userBean);
                        TextHelper.showText("订阅成功");
                    }
                }
                break;
            case "点赞":
                int likeCount = bookListBean.getCollectorCount()+1;
                bookListBean.setCollectorCount(likeCount);
                mBookListService.updateEntity(bookListBean);
                TextHelper.showText("点赞成功");
                mBookListBeans = mBookListService.getAllVisibleBookLists();
                mBookListAdapter.refreshItems(mBookListBeans);

                break;
            case "删除":
                if(userBean.getAdmin()!=1){
                    TextHelper.showLongText("你不是管理员无法删除书单");
                }else {
                    mBookListService.deleteBookListCollect(bookListBean);
                    mBookListService.deleteEntity(bookListBean);
                }
                break;
            default:
                break;
        }
    }

}
